<template>
  <div class="dataupload">
    <el-row>
      <el-col :span="22">
        <h2 style="text-align: center;">上传人员清单</h2>
      </el-col>
      <el-col :span="2">
        <div style="margin-top: 20px">
          <el-button style="width: 100px;" type="primary" @click="getBack">返回</el-button>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <div style="width: 1000px;margin: 0 auto 20px;display: flex;align-items: center">
          <div style="margin-right: 10px">二者选一</div>
          <el-radio-group v-model="radio" @change="getRadio">
            <el-radio :label="0">单个新增</el-radio>
            <el-radio :label="1">批量上传</el-radio>
          </el-radio-group>
        </div>
      </el-col>
    </el-row>
    <!--  <el-row ><el-col :span="24">-->
    <!--   <div style="width: 1000px;margin: 0 auto 20px"> <el-button-->
    <!--     style="width: 130px"-->
    <!--     icon="el-icon-plus"-->
    <!--     size="small"-->
    <!--     type="primary"-->

    <!--     plain-->
    <!--     @click="handleUpload" >批量新增</el-button></div>-->
    <!--  </el-col></el-row>-->
    <el-form v-if="isShow" ref="form" :model="form" :rules="rules" label-width="110px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="雇员姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入雇主姓名"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="雇员性别" prop="sex">
            <el-select v-model="form.sex" placeholder="请选择">
              <el-option
                  v-for="dict in sexOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="证件类型" prop="id_card_type_id">
            <el-select v-model="form.id_card_type_id" placeholder="请选择">
              <el-option
                  @click.native="getCardType(item)"
                  v-for="item in idCardTypeList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                  :disabled="item.status === '0'"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="证件号码" prop="id_card_no">
            <el-input v-model="form.id_card_no" placeholder="请输入证件号码"/>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row>
        <!--          TODO 做成选择-->
        <el-col :span="12">
          <el-form-item label="工种类别" prop="type">
            <!--            <treeselect style="width: 250px" v-model="form.industryId" @select="selectDepart" :options="industryOptions"-->
            <!--                        :normalizer="normalizer" placeholder="请选上级分类"/>-->
            <el-select v-model="form.type" placeholder="请选择">
              <el-option
                  v-for="item in TypeworkId"
                  :key="item.dictValue"
                  :value="item.dictValue"
                  :label="item.dictLabel"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="健康情况" prop="health_cond">
            <el-input v-model="form.health_cond" placeholder="请输入健康状况"/>
            <!--            <el-select v-model="form.health_cond" placeholder="请选择">-->
            <!--              <el-option-->
            <!--                  v-for="item in healthy"-->
            <!--                  :key="item.dictValue"-->
            <!--                  :value="item.dictValue"-->
            <!--                  :label="item.dictLabel"-->
            <!--              />-->
            <!--            </el-select>-->
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="月收入" prop="income_month">
            <el-input v-model="form.income_month" placeholder="请输入月收入"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="保费" prop="price">
            <el-input v-model="form.price" placeholder="请输入保费"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="岗位名称" prop="industry_name">
            <el-input v-model="form.industry_name" placeholder="请输入岗位名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用工单位" prop="company">
            <el-input v-model="form.company" placeholder="请输入用工单位"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="18">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" :rows="5" placeholder="请输入备注内容"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="状态 " prop="status">
        <el-radio-group v-model="form.status">
          <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
          >{{ dict.dictLabel }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <div class="dialog-footer">
        <el-button type="info" @click="cancel('form')">重置</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>

      </div>
    </el-form>
    <!--  <el-dialog :title="upload.title" :visible.sync="upload.open1" width="900px" append-to-body>-->
    <div v-else style="margin:50px auto 0;width: 600px;text-align: center">
      <!--     accept=".csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"-->
      <el-upload
          ref="upload"
          class="upload-demo"
          action="/"
          :limit="1"
          :on-exceed="formHandleExceed"
          :file-list="formFileList"
          :on-remove="formHandleRemove"
          :http-request="handleUpdateForm"
          :before-upload="beforeUploadForm"
          :auto-upload="false"
          drag
      >
        <img src="../../../assets/images/Import.png" style="width: 83px;height: 91px;margin: 50px 0;"/>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="display: flex;justify-content: space-between;width: 600px;" slot="tip">
          <div class="el-upload__tip" style="color:red" slot="tip">仅允许导入“xls”或“xlsx”格式文件！</div>
          <span style="width: 200px;;display: inline-block"></span>
          <el-link type="info" style="font-size:12px;color: #00afff;" @click="importTemplate">下载模板</el-link>
        </div>

      </el-upload>
      <div slot="footer" style="display: flex;justify-content: flex-end">
        <el-button type="primary" style="width: 100px" @click="submitFileForm">确 定</el-button>
        <el-button type="info" style="width: 100px" @click="upload.open1 = false">取 消</el-button>
      </div>
    </div>
    <!--  </el-dialog>-->
  </div>
</template>

<script>
import {addUser, addUser1, updateUser, getUser, importTemolate, importTemolate1, batchSave} from "@/api/insurance/user";
import {listIdCardType, get_card_type} from "@/api/base/idCardType";
import {listIndustry} from "@/api/insurance/industry";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {get_base_industry} from "@/api/insurance/repordRecord"

export default {
  name: "dataUpload",
  data() {
    return {
      //选择新增条件
      radio: 0,
      isShow: true,//二者选一
      // 状态 字典
      statusOptions: [],
      formMaxSize: 10,//上传文件大小
      formFileList: [],
      uploadFormFileList: [],//确定上传文件
      //性别  字典
      sexOptions: [],
      //证件类型
      idCardTypeList: [],

      // 表单参数
      form: {
        class_type: 1,//区分单个新增或是批量新增
        // insureId:null, //投保id
        eli_id: '',//方案id
        user_id: '',//操作人id
        name: null,//雇主姓名
        sex: null,//性别
        id_card_type_id: 1,//证件类型
        // idCardTypeName: null,//证件类型名称
        id_card_no: null,//证件号码
        type: null,//工种id(1:1-3类；2：4类)
        // industryName: null,//健康情况
        health_cond: '',//健康情况
        income_month: null,//月收入
        company: null,//用工单位
        industry_name: null,//职务名称
        remark: null,//备注
        price: null,//保费
        status: "0"
      },
      // 表单校验
      rules: {
        name: [
          {required: true, message: '请输入雇主姓名', trigger: 'blur'},
        ],
        sex: [
          {required: true, message: '请选择性别', trigger: 'change'}
        ],
        id_card_type_id: [
          {required: true, message: '请选择证件类型', trigger: 'change'}
        ],
        id_card_no: [
          {required: true, message: "证件号码不能为空", trigger: "blur"},
          {pattern: /(^\d{15}$)|(^\d{17}([0-9]|X)$)/, message: '请输入正确的证件号码'}
        ],
        type: [
          {required: true, message: '请选择工种类别', trigger: 'change'}
        ],
        health_cond: [
          {required: true, message: '请选择健康情况', trigger: 'blur'}
        ],
        income_month: [
          {required: true, message: "请输入月收入", trigger: "blur"}
        ],
        price: [
          {required: true, message: "请输入保费", trigger: "blur"}
        ],
        industry_name: [
          {required: true, message: "请输入职务名称", trigger: "blur"}
        ],
        company: [
          {required: true, message: "请输入用工单位", trigger: "blur"}
        ],
        remark: [
          {required: false, message: "请输入用工单位", trigger: "blur"}
        ],
        status: [
          {
            required: true, message: '请选择状态', trigger: 'change'
          }

        ],

      },
      healthy: [],//健康状况
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open1: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否更新已经存在的用户数据
        isSupportUpdate: false,
      },
      // 职业分类树选项
      industryOptions: [],
      //工种类型
      TypeworkId: [],
    }
  },
  created() {
    // this.form.insureId=this.$store.state.user.infoUser.id;
    this.form.user_id = JSON.parse(localStorage.getItem('userInfo')).userId;
    var id = this.$route.query.programme;
    this.form.eli_id = localStorage.getItem('PolicyID');
    // console.log('PolicyID',PolicyID)
    if (id != undefined) {
      // this.form.eli_id = id.bid
    }
    this.getDicts("industry_type").then(response => {
      this.TypeworkId = response.data;
      // console.log('TypeworkId', this.TypeworkId)
    });
    this.getDicts("common_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_user_sex").then(res => {
      this.sexOptions = res.data;
    });
    // this.getDicts("health_cond").then(res => {
    //   this.healthy = res.data;
    //   // console.log('healthy', this.healthy)
    // });
    // this.getDicts("health_cond").then(res => {
    //   this.healthOptions = res.data;
    // });
    // this.getDicts("industry_type").then(res => {
    //   this.industryTypeOptions = res.data;
    // });
    this.getIdcardTypeList();
    this.getTreeselect();
  },
  components: {
    Treeselect
  },
  methods: {
    getRadio(e) {
      console.log('eee', e)
      if (e == 0) {
        this.isShow = true;
      } else {
        this.isShow = false;
      }
    },
    /** 转换职业分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },

    /** 查询部门下拉树结构 */
    getTreeselect() {
      get_base_industry().then(response => {
        this.industryOptions = [];
        const data = {id: 0, name: '顶级节点', children: []};
        data.children = this.handleTree(response.data, "id", "parent_id");
        this.industryOptions.push(data);
        // console.log('工种名称', response);
        // console.log('industryOptions', this.industryOptions);
      });
    },
    //选择工种名称
    selectDepart(e) {
      this.form.industryName = e.name
    },
    //上传文件导入
    handleUpload() {
      this.upload.title = "投保用户批量添加";
      this.upload.open1 = true;
    },
    //开始上传前验证
    beforeUploadForm(file) {
      // console.log('验证', file)
      //文件大小验证
      if (file.size / 1024 / 1024 > this.formMaxSize) {
        this.$message({
          message: `上传文件大小不能超过${this.formMaxSize}M!`,
          type: 'waning'
        })
        false
      }
      //  中文乱码处理
      if (file.raw) {
        let reader = new FileReader()//读取文件内容
        reader.readAsText(file.raw, 'gb2312')//防止中文乱码问题，不加reader.onload方法都不会触发
        reader.onload = function (e) {
          this.contentHtml = e.target.result;//txt文本内容，接下来就可以对其进行校验处理了
          // console.log('contentHtml', this.contentHtml);
        }
      }
      //验证文件类型
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension = testmsg === 'xlsx' || testmsg === 'xls' || testmsg === 'csv'
      if (!extension) {
        this.$message({
          message: '上传文件只能是xlsx/xls/csv格式',
          type: 'warning'
        })

      }
      return extension
    },
    //移除上传列表中的文件
    formHandleRemove(file, formFileList) {
      let that = this;
      for (let i = 0; i < that.uploadFormFileList.length; i++) {
        if (that.uploadFormFileList[i].pname === file.name) {
          that.uploadFormFileList.splice(i, 1);
          break;
        }
      }
    },
    // 下载文件
    importTemplate() {
      var obj = {
        type: '2'
      }
      const loading = this.$loading({
        lock: true,
        text: '请耐心等待正在下载模板',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      importTemolate1(obj).then(res => {
        // console.log('用户批单模板', res)
        if (res.code == 1) {
          loading.close();
          let link = document.createElement('a'); // 创建a标签
          link.style.display = 'none';
          let objectUrl = res.data;
          link.href = objectUrl;
          link.click();
        }
        // this.download(res.msg);
      })
    },
    //上传导入确定按钮
    submitFileForm() {
      this.$refs.upload.submit();
      // this.$refs.upload.submit();
    },
    // 允许上传文件个数验证
    formHandleExceed(files, formFileList) {
      // console.log('files', files)
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + formFileList.length} 个文件`)
    },

    //上传文件
    handleUpdateForm(param) {
      // console.log('param', param)
      // console.log('isSupportUpdate',this.upload)
      let that = this;
      let formData = new FormData();
      // console.log('id', that.form.insureId)
      formData.append('eli_id', that.form.eli_id)//额外参数
      formData.append('excel', param.file);
      // formData.append('isSupportUpdate',that.upload.isSupportUpdate),
      formData.append('class_type', '2');
      formData.append('user_id', that.form.user_id);
      // console.log('plan_id',  that.form.plan_id);
      // console.log('user_id', that.form.user_id);
      // console.log('param', formData);
      // console.log('param', formData);
      var obj = {
        status: 0
      }
      const loading = this.$loading({
        lock: true,
        text: '请耐心等待正在上传数据',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      addUser1(formData).then(response => {
        // console.log('response方案', response)
        loading.close();
        var that = this;
        if (response.code == 1) {
          console.log('response', response)
          that.$confirm(response.msg, '标题名称', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            callback: action => {
              // console.log('action1',action)
              if (response.data.length == 0) {
                that.$router.push({
                  path: '/insurancemanagement/user1',
                  // path: '/business/user/index',
                  query: {
                    insureInfo1: obj
                  }
                })
              } else {
                setTimeout(() => {
                  that.$confirm('是否要将添加用户部分错误的信息导出', '标题名称', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    callback: action => {
                      // console.log('234255',action)
                      if (action == 'confirm') {
                        let link = document.createElement('a'); // 创建a标签
                        link.style.display = 'none';
                        let objectUrl = response.data;
                        link.href = objectUrl;
                        link.click();

                      }
                    }
                  });
                }, 500)

              }
            }
          });

        }
        if (response.code == 0) {
          console.log('response', response)
          if(response.data.length!=0){
            that.$confirm(response.msg, '标题名称', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              callback: action => {
                // console.log('action1',action)
                if (response.data.length!=0) {
                  setTimeout(() => {
                    that.$confirm('是否要将添加用户部分错误的信息导出', '标题名称', {
                      confirmButtonText: '确定',
                      cancelButtonText: '取消',
                      callback: action => {
                        // console.log('234255',action)
                        if (action == 'confirm') {
                          let link = document.createElement('a'); // 创建a标签
                          link.style.display = 'none';
                          let objectUrl = response.data;
                          link.href = objectUrl;
                          link.click();
                        }
                      }
                    });
                  }, 500)

                }
              }
            });
          }


        }

        // console.log('234325', response)

      })

    },
    //查询证件类型
    getIdcardTypeList() {
      get_card_type().then(res => {
        this.idCardTypeList = res.data
      })
    },
    //取消
    cancel(form) {
      this.$refs[form].resetFields();
    },
    //点击对应的证件类型
    getCardType(item) {
      this.form.idCardTypeId = item.id;
      this.form.idCardTypeName = item.name;
      // console.log('item', item)
    },
    getBack() {
      this.$router.back(-1);
    },
    submitForm(form) {
      var obj = {
        status: 0
      }

      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log('form', this.form);
          addUser1(this.form).then(response => {
            if (response.code == 1) {
              this.msgSuccess(response.msg);
              // this.open = false;
              this.$router.push({
                path: '/insurancemanagement/user1',
                // path: '/business/user/index',
                query: {
                  insureInfo1: obj
                }
              })
            }

            // console.log('新增', response)
            // this.getQueryUser();
          });
        }
      });
    }
  }
}
</script>

<style scoped>
.dataupload{
  background: #F8FBFF;
  padding:30px;
  border-radius: 10px;
  box-sizing: border-box;
  margin: 40px;
}
.el-form {
  width: 1000px;
  /*height: 800px;*/
  margin: 0 auto;
  /*background-color: #4AB7BD;*/
}

.dialog-footer {
  /*background-color: pink;*/
  text-align: center;
}

.el-input {
  width: 220px;
}

.el-button {
  width: 200px;
}
</style>

